package com.cw.jeeyt.service.impl.security;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.cw.jeeyt.common.pojo.TreeNode;
import com.cw.jeeyt.common.utils.StringUtils;
import com.cw.jeeyt.service.bo.security.SecurityOrgBo;
import com.cw.jeeyt.service.bo.security.SecurityUserBo;
import com.cw.jeeyt.core.util.SessionUtil;
import com.cw.jeeyt.dao.intf.security.SecurityOrgDao;
import com.cw.jeeyt.dao.model.security.SecurityOrgDo;
import com.cw.jeeyt.service.converter.security.SecurityOrgConverter;
import com.cw.jeeyt.service.intf.security.SecurityOrgService;
import com.cw.jeeyt.service.utils.DataDicUtils;
import com.cw.lang.common.utils.CollectionUtil;
import com.cw.lang.mybatis.dto.PageInfo;

/**
 * 组织机构表业务实现类
 *
 * @author chenw
 * @version 1.0.0
 */
@Service
public class SecurityOrgServiceImpl implements SecurityOrgService {

    private static final Logger logger = LoggerFactory.getLogger(SecurityOrgServiceImpl.class);
    @Autowired
    private SecurityOrgDao securityOrgDao;

    /**
     * 分页查询组织机构表
     *
     * @param securityOrgBo
     * @param startNum
     * @param pageSize
     * @return
     * @throws Exception
     */
    @Override
    public PageInfo<SecurityOrgBo> queryByPage(SecurityOrgBo securityOrgBo, Integer startNum, Integer pageSize)
    throws Exception {

        if (securityOrgBo == null) {
            logger.error("组织机构表为空");
            return null;
        }
        PageInfo<SecurityOrgDo> pageInfo = securityOrgDao.queryByPage(SecurityOrgConverter.bo2Do(securityOrgBo),
            startNum, pageSize);
        List<SecurityOrgBo> securityOrgBos = SecurityOrgConverter.doList2BoList(pageInfo.getList());
        if (CollectionUtil.isNotEmpty(securityOrgBos)) {
            Map<String, Object> dictMap = new HashMap<>();
            dictMap.put("orgType", "org_type");
            JSONArray jsonArray = DataDicUtils.convertDict(JSON.parseArray(JSON.toJSONString(securityOrgBos)), dictMap);
            securityOrgBos = JSON.parseArray(jsonArray.toJSONString(), SecurityOrgBo.class);
        }
        return new PageInfo<>(pageInfo, securityOrgBos);
    }

    /**
     * 根据主键查寻组织机构表信息
     *
     * @param orgId
     * @return
     */
    @Override
    public SecurityOrgBo getSecurityOrgById(Long orgId) throws Exception {

        if (orgId == null) {
            logger.error("--主键orgId为空--");
            return null;
        }
        return SecurityOrgConverter.do2Bo(securityOrgDao.getById(orgId));
    }

    /**
     * 新增组织机构表
     *
     * @param securityOrgBo
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Integer insert(SecurityOrgBo securityOrgBo) throws Exception {

        if (securityOrgBo == null) {
            logger.error("组织机构表为空");
            return null;
        }
        SecurityUserBo userVo = SessionUtil.getSessionUser();
        SecurityOrgDo systemOrg = SecurityOrgConverter.bo2Do(securityOrgBo);
        systemOrg.setCreateBy(userVo.getId());
        systemOrg.setCreateDate(new Date());
        systemOrg.setUpdateBy(userVo.getId());
        systemOrg.setUpdateDate(new Date());
        return securityOrgDao.insertBySelective(systemOrg);
    }

    /**
     * 更新组织机构表信息
     *
     * @param securityOrgBo
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void update(SecurityOrgBo securityOrgBo) throws Exception {

        if (securityOrgBo == null) {
            logger.error("组织机构表为空");
            return;
        }
        SecurityUserBo userVo = SessionUtil.getSessionUser();
        SecurityOrgDo systemOrg = SecurityOrgConverter.bo2Do(securityOrgBo);
        systemOrg.setUpdateBy(userVo.getId());
        systemOrg.setUpdateDate(new Date());

        securityOrgDao.update(systemOrg);
    }

    /**
     * 删除组织机构表
     *
     * @param securityOrgBo
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(SecurityOrgBo securityOrgBo) throws Exception {

        if (securityOrgBo == null) {
            logger.error("组织机构表为空");
            return;
        }
        securityOrgDao.delete(SecurityOrgConverter.bo2Do(securityOrgBo));
    }

    /**
     * 根据父机构id查询子节点信息
     *
     * @param orgParentId
     * @return
     * @throws Exception
     */
    @Override
    public List<SecurityOrgBo> querySecurityOrgListByParentId(Long orgParentId) throws Exception {
        return SecurityOrgConverter.doList2BoList(securityOrgDao.querySecurityOrgListByParentId(orgParentId));
    }

    /**
     * 更新机构的上级机构
     *
     * @param orgId
     * @param orgParentId
     * @throws Exception
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateOrgParentId(Long orgId, Long orgParentId) throws Exception {
        if (orgId == null) {
            logger.error("主键orgId为空");
            return;
        }
        if (orgParentId == null) {
            logger.error("父节点id为空");
            return;
        }
        securityOrgDao.updateOrgParentId(orgId, orgParentId);
    }

    /**
     * 更新机构名称
     *
     * @param orgId
     * @param orgName
     * @throws Exception
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateOrgName(Long orgId, String orgName) throws Exception {
        if (orgId == null) {
            logger.error("主键id为空");
            return;
        }
        if (StringUtils.isEmpty(orgName)) {
            logger.error("组织机构名称为空");
            return;
        }
        securityOrgDao.updateOrgName(orgId, orgName);
    }

    /**
     * 查询组织机构组织机构树json数据
     *
     * @param orgParentId
     * @param parentIsOpen
     * @param childIsOpen
     * @return
     * @throws Exception
     */
    @Override
    public String queryOrgJson(Long orgParentId, boolean parentIsOpen, boolean childIsOpen) throws Exception {
        SecurityOrgDo securityOrg = securityOrgDao.getById(orgParentId);
        if (securityOrg == null) {
            throw new Exception("上级资源信息为空:" + orgParentId);
        }
        //加载根部组织机构信息
        List<SecurityOrgDo> securityOrgList = securityOrgDao.queryOrgList();
        List<TreeNode> treeNodeList = new ArrayList<TreeNode>();
        TreeNode parentTreeNode = new TreeNode();
        parentTreeNode.setId(securityOrg.getOrgId());
        parentTreeNode.setName(securityOrg.getOrgName());
        parentTreeNode.setOpen(true);
        parentTreeNode.setComment(securityOrg.getOrgComment());
        treeNodeList.add(parentTreeNode);
        if (securityOrgList != null && !securityOrgList.isEmpty()) {
            for (SecurityOrgDo sm : securityOrgList) {
                if (sm.getOrgId()
                    .equals(orgParentId)) {
                    continue;
                }
                TreeNode childTreeNode = new TreeNode();
                childTreeNode.setId(sm.getOrgId());
                childTreeNode.setName(sm.getOrgName());
                childTreeNode.setpId(sm.getOrgParentId());
                childTreeNode.setComment(sm.getOrgComment());
                childTreeNode.setOpen(false);
                treeNodeList.add(childTreeNode);
            }
        }
        return JSON.toJSONString(treeNodeList);
    }

    /**
     * 查询组织机构根节点信息
     *
     * @return
     * @throws Exception
     */
    @Override
    public SecurityOrgBo queryRootSecurityOrg() throws Exception {
        return SecurityOrgConverter.do2Bo(securityOrgDao.queryRootSecurityOrg());
    }

    /**
     * 查询组织机构列表
     */
    @Override
    public List<SecurityOrgBo> queryOrgList() {
        return SecurityOrgConverter.doList2BoList(securityOrgDao.queryOrgList());
    }
}
